package com.wg.generator.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.wg.generator.entity.ClassInfo;
import com.wg.generator.entity.DownloadParam;
import com.wg.generator.entity.ParamInfo;
import com.wg.generator.entity.ReturnT;
import com.wg.generator.service.GeneratorService;
import com.wg.generator.util.TableParseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * code generator
 *
 * @author lihc14
 */
@Controller
@Slf4j
public class IndexController {

    @Autowired
    private GeneratorService generatorService;

    @RequestMapping("/")
    public String index() {
        return "index";
    }

    @PostMapping("/genCode")
    @ResponseBody
    public ReturnT codeGenerate(@RequestBody ParamInfo paramInfo, HttpServletRequest request) throws Exception {
        if (paramInfo.getTableSql().trim().length() < 1) {
            return ReturnT.ERROR("表结构信息不可为空");
        }

        //1.Parse Table Structure 表结构解析
        ClassInfo classInfo = TableParseUtil.processTableIntoClassInfo(paramInfo);

        //2.Set the params 设置表格参数
        Map<String, Object> params = new HashMap<String, Object>(8);
        params.put("classInfo", classInfo);
        params.put("tableName", classInfo == null ? System.currentTimeMillis() : classInfo.getTableName());
        params.put("authorName", paramInfo.getAuthorName());
        params.put("packageName", paramInfo.getPackageName());
        params.put("swagger", Convert.toBool(paramInfo.getSwagger(), false));
        classInfo.setSerialVersionUID(IdUtil.getSnowflake(1, 1).nextId());

        log.info("generated table:" + classInfo.getTableName() + ",field size:" + (classInfo.getFieldList() == null ? "" : classInfo.getFieldList().size()));

        //3.generate the code by freemarker template and param . Freemarker根据参数和模板生成代码
        Map<String, String> result = generatorService.getResultByParams(params, request);

        return ReturnT.SUCCESS(result);
    }

    @RequestMapping("/downloadFile")
    @ResponseBody
    public ReturnT download(@RequestBody DownloadParam downloadParam, HttpServletRequest request) {
        String retVal = generatorService.downloadFile(downloadParam, request);
        if (StrUtil.isBlank(retVal)) {
            return ReturnT.SUCCESS();
        }
        return ReturnT.ERROR(retVal);
    }
}
